#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFFER_SIZE (200)
#define HEAD_SIZE (50) 

#define SRV_PORT (9090)
#define SRV_IP "127.0.0.1"


int main()
{
    int srv_socket;
    int state;
    struct sockaddr_in srv_addr;
    struct sockaddr_in *ptr_srv_addr = &srv_addr;

    char buffer[BUFFER_SIZE];
    char rcv_buff[HEAD_SIZE+BUFFER_SIZE];

    // Create socket.
    srv_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(0 > srv_socket)
    {
        printf("Create socket error!\n");
        exit(-1);
    }

    memset(ptr_srv_addr, 0, sizeof(srv_addr));
    srv_addr.sin_family = AF_INET;
    srv_addr.sin_addr.s_addr = inet_addr(SRV_IP);
    srv_addr.sin_port = htons(SRV_PORT);

    // Connect with server socket.
    state = connect(srv_socket, ptr_srv_addr, sizeof(srv_addr));
    if(0 > state)
    {
        printf("Connect server error!\n");
        exit(-1);
    }

    while(1)
    {
        puts("Send:");
        fgets(buffer, BUFFER_SIZE, stdin);
        buffer[BUFFER_SIZE-1] = '\0';
        buffer[strlen(buffer)-1] = '\0';
        if(0 == strcmp("quit", buffer))
        {
            write(srv_socket, buffer, sizeof(buffer));
            puts("Finish send.");
            break;
        }

        puts("------>");
        puts("<------");

        write(srv_socket, buffer, sizeof(buffer));

        read(srv_socket, rcv_buff, sizeof(rcv_buff));

        printf("Receive:\n\"%s\"\n", rcv_buff);
        puts("-------");
    }
    close(srv_socket);
    return 0;
}
